package cn.ilikes.tools.nosql.jpa.clients.indexs.index;

import java.io.File;

import java.io.IOException;

import org.apache.lucene.store.Directory;
import org.apache.lucene.store.FSDirectory;
import org.slf4j.Logger;

import cn.ilikes.tools.logs.Loggerfactory;
import cn.ilikes.tools.nosql.jpa.SysConfigs;
import cn.ilikes.tools.nosql.jpa.clients.indexs.index.hadoops.LocalSystemDirectory;
import cn.ilikes.tools.nosql.jpa.configs.indexs.IndexConfigs;

public class LuceneLocalIndexSource extends ABLuceneIndexSource {

	private Logger logger = Loggerfactory.instance(LuceneLocalIndexSource.class);

	private Directory directory;

	public LuceneLocalIndexSource(IndexConfigs indexConfigs) {
		super(indexConfigs);

	}

	private void setDirectory(Directory directory) {
		this.directory = directory;
	}

	@Override
	protected Directory getLuceneDirectory() {

		return directory;
	}

	private String getProperties(String key) {
		IndexConfigs indexConfigs = getIndexConfigs();
		return indexConfigs.getProperties().getProperty(key);
	}

	@Override
	public void init() {
		Loggerfactory.info(logger, "Start init Lucene Index Source ");
		try {
			String luceneDirPath = getProperties(SysConfigs.index_save_path);
			Directory directory = FSDirectory.open(createIndexDirectory(luceneDirPath));
//			Directory directory = new LocalSystemDirectory(createIndexDirectory(luceneDirPath));
			setDirectory(directory);
			Loggerfactory.info(logger, "init Lucene Index Source success ! ");
		} catch (IOException e) {
			Loggerfactory.error(logger, e);
		}
	}

	@Override
	public void close() {
		Loggerfactory.info(logger, "Start Close Lucene Index Source ");
		try {
			directory.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	private File createIndexDirectory(String luceneDirPath) {

		File file = new File(luceneDirPath);
		if (file.exists()) {
			Loggerfactory.info(logger, "use luence index dir path  :  " + luceneDirPath);
			return file;
		}
		if (!file.isDirectory()) {
			{
				Loggerfactory.info(logger, "create  luence index dir path  :  " + luceneDirPath);
				file.mkdirs();
			}
		}

		return file;

	}

	@Override
	public void open() {
		Loggerfactory.info(logger, "Start open  Lucene Index Source ");

	}

}
